from random import randint

from django.shortcuts import render

# Create your views here.
# 访问方式： GET /sms_codes/(?P<mobile>1[3-9]\d{9})/
from django_redis import get_redis_connection
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from celery_tasks.sms.tasks import send_sms_code

# 访问方式： GET /sms_codes/(?P<mobile>1[3-9]\d{9})/
from user.models import User
from user.serializers import UserSerializer
from yipin.libs.yuntongxun.sms import CCP


class SMSCodeView(APIView):
    """
    发送短信验证码
    传入参数：
        mobile, image_code_id, text
    """
    def get(self, request, mobile):

        # 判断60s
        # 建立链接
        conn = get_redis_connection('verify')
        flag = conn.get('sms_flag_%s'%mobile)
        if flag:
            return Response({'message':'error'}, status=401)
        # 生成短信验证码
        sms_code = '%06d'%randint(0, 999999)
        print(sms_code)
        # 保存短信到redis缓存中
        # 使用redis管道: 提高redis效率
        pl = conn.pipeline()
        pl.setex('sms_code_%s'%mobile, 300, sms_code)
        pl.setex('sms_flag_%s'%mobile, 60, 1)
        pl.execute()

        # 发送短信
        send_sms_code.delay(mobile, sms_code)
        # 结果返回
        print(sms_code)
        return Response({'message': 'ok'})


#   GET   usernames/17356723320/count/
class UsernameCountView(APIView):
    """判断账号是否存在"""
    def get(self, request, username):
        count = User.objects.filter(username = username ).count()

        data = {
            'usernames':username,
            'count':count
        }
        return Response(data)


#  GET mobiles/17356723320/count/
class MobileCountView(APIView):
    """手机号查询"""
    def get(self, request, mobile):
        count = User.objects.filter(mobile = mobile).count()

        return Response({
            'mobile':mobile,
            'count':count
        })


class UserView(CreateAPIView):
    serializer_class = UserSerializer